// redbox/redbox.js
const app = getApp();
const utils = require('../utils/util.js')
const CryptoJS = require('../utils/aes-jia.js');
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    list:{
      type: Array,
      value:[]
    },
    actid:{
      type:String,
      value:""
    },
    userInfo:{
      type:JSON,
      value:{}
    },
    walletBalance:{
      type:null,
      value:''
    },
    whetherSetPayPwd:{
      type:Boolean,
      value:false
    },
    login: {
      type:Boolean,
      value:false,
    },
    phone: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    index:null,
    payment: 0,
    redId: '',
    shareshow: false,
    list: [],
    totalPages: '',
    pageNumber: 1,
    inputname: '',
    userInfo: {},
    openShow: false,
    returnShow: false,
    gobackShow: false,
    receiveShow: false,
    groupShow: false,
    myred: false,
    myshow: '',
    group: '',
    groupList: {},
    isOpen: false,
    sendUrl: '',
    sendName: '',
    redBlessings: '',
    receiveName: '',
    receiverUrl: '',
    type: 1,
    redPacket: '',
    amountRedEnvelope: '',
    amountRedEnvelopeico: '',
    givingAdvice: '',
    walletBalance: '',
    payFocus: false,
    showPayPwdInput: false,
    pwdVal: '',
    isOver: true,
    senderId: '',
    returninput: '',
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 专属红包
    reddetails(e) {
      var that = this
      that.setData({
        group:'',
        index: e.currentTarget.dataset.index
      })
      var datatg = e.currentTarget.dataset
      console.log('活动id',that.data.actid,'个信息',that.data.userInfo)
      if (datatg.receiveid == that.data.userInfo.id) {
        app.req({
          url: "blessmini/redPacket/redPacketDetails",
          data: {
            id: datatg.id
          },
          method: "post",
          success: function (res) {
            if (res.code == 200) {
              if (res.data.isOpen == 0) {
                that.setData({
                  openShow: true,
                })
              } else if (res.data.isOpen == 1 || res.data.isOpen == 2 || res.data.isOpen == 4) {
                that.setData({
                  receiveShow: true,
                })
              }
              if (res.data.openTime) {
                var time = utils.getTime(res.data.openTime)
              }
              that.setData({
                sendUrl: res.data.senderUrl,
                sendName: res.data.senderName,
                redBlessings: res.data.content,
                redId: res.data.id,
                receiveName: res.data.receiverName,
                receiveUrl: res.data.receiverUrl,
                redPacket: res.data.money,
                sendTime: time,
                senderId: res.data.sendId,
                isOpen: true,
              })
            }
          }
        })
      } else {
        that.setData({
          openShow: true,
          isOpen: false,
          sendUrl: datatg.sendavatarurl,
          sendName: datatg.sendname,
          redBlessings: datatg.content,
        })
      }
    },
    payment(e) {
      var id = e.currentTarget.dataset.index
      this.setData({
        payment: id
      })
    },
    myreddetails(e) {
      var that = this
      var datatg = e.currentTarget.dataset
      console.log(datatg)
      app.req({
        url: "blessmini/redPacket/redPacketDetails",
        data: {
          id: datatg.id
        },
        method: "post",
        success: function (res) {
          if (res.code == 200) {
            that.setData({
              sendUrl: res.data.senderUrl,
              sendName: res.data.senderName,
              redBlessings: res.data.content,
              redPacket: res.data.money,
              isOpen: true,
              myshow: datatg.isopen,
              type: 1,
              receiveShow: true,
              myred: true,
            })
          }
        }
      })
    },
    seegroup() {
      this.groupdetails(this.data.redId)
      this.setData({
        groupShow: true
      })
    },
    groupbtn(e) {
      var that = this
      var datatg = e.currentTarget.dataset
      if (datatg.isopen == 0) {
        that.setData({
          isOpen: true,
          openShow: true,
          group: 1,
        })
      } else {
        that.setData({
          groupShow: true
        })
        that.groupdetails(datatg.id)
      }
      that.setData({
        sendUrl: datatg.sendavatarurl,
        sendName: datatg.sendname,
        redBlessings: datatg.content,
        redId: datatg.id
      })
    },
    groupdetails(e) {
      var that = this
      var redid = e
      app.req({
        url: "blessmini/redPacket/groupPacketDetails",
        data: {
          id: redid,
          pageNumber: 1,
          pageSize: 10,
        },
        method: "post",
        success: function (res) {
          if (res.code == 200) {
            if (res.data.openTime) {
              var time = utils.getTime(res.data.openTime)
            }
            that.setData({
              sendUrl: res.data.senderUrl,
              sendName: res.data.senderName,
              redBlessings: res.data.content,
              redId: res.data.id,
              groupList: res.data,
            })
          }
        }
      })
    },
    onClose(){
      this.setData({
        showPopup: false,
      })
    },
    xClose() {
      this.setData({
        openShow: false,
      })
    },
    xClose1() {
      this.setData({
        receiveShow: false,
      })
    },
    xClosetwo() {
      this.setData({
        gobackShow: false,
      })
    },
    xClose2() {
      this.setData({
        returnShow: false,
      })
    },
    xClose3() {
      this.setData({
        groupShow: false,
      })
    },
    openRed() {
      var that = this
      var url = ''
      var data = {}
      if (that.data.group == 1) {
        url = 'blessmini/redPacket/rob'
        data = {
          bigId: that.data.redId
        }
      } else {
        url = 'blessmini/redPacket/receiveRedPrivate'
        data = {
          redPrivateId: that.data.redId
        }
      }
      app.req({
        url: url,
        data: data,
        method: "post",
        success: function (res) {
          if (res.code == 200) {
            wx.showToast({
              title: '领取成功',
            })
            if (that.data.group == 1) {
              that.setData({
                openShow: false,
                groupShow: true,
              })
              that.groupdetails(that.data.redId)
              that.emit()
            } else {
              that.data.list[that.data.index].isOpen=1
              that.setData({
                openShow: false,
                receiveShow: true,
                list:that.data.list
              })
            }
            // that.emit()
            // that.onShow()
          }
        }
      })
    },
    returnBtn() {
      this.setData({
        openShow: false,
        returnShow: true,
      })
    },
    //感谢
    returninput(e) {
      this.setData({
        returninput: e.detail.value
      })
    },
    returnRed() {
      var that = this
      if (that.data.returninput == '') {
        that.setData({
          returninput: '谢谢您的好意'
        })
      }
      app.req({
        url: "blessmini/redPacket/returnRedPrivate",
        method: "post",
        data: {
          id: that.data.redId,
          birthId: that.data.actid,
          content: that.data.returninput,
        },
        success: function (res) {
          if (200 == res.code) {
            wx.showToast({
              title: "红包已退回",
              duration: 2000
            })
            that.data.list[that.data.index].isOpen = 3
            that.setData({
              returnShow: false,
              list: that.data.list
            })
            // that.onShow()
            // that.emit()
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    },
    returnCeremony() {
      var that = this
      that.setData({
        gobackShow: true,
        receiveShow: false,
      })
    },
    //输入金额
    amountInput: function (e) {
      e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
      console.log('bug1')
      if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
        e.detail.value = parseFloat(e.detail.value);
      } else if (e.detail.value.indexOf(".") == 0) {
        console.log('bug2')
        e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
        e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
      }
      if (e.detail.value > 500000) {
        console.log('bug3')
        e.detail.value = 500000
      }
      this.setData({
        amountRedEnvelope: e.detail.value,
      })

    },
    amountblur(e) {
      if (e.detail.value !== '') {
        this.setData({
          amountRedEnvelopeico: '￥' + this.data.amountRedEnvelope
        })
      }
    },
    returnfocus(e) {
      this.setData({
        amountRedEnvelopeico: ''
      })
    },
    givingAdviceInput: function (e) {
      this.setData({
        givingAdvice: e.detail.value.replace(/\s+/g, '')
      })
    },
    returnCeremonySelection: function (e) {
      var that = this;
      if (that.data.amountRedEnvelope == 0 || that.data.amountRedEnvelope.length == 0) {
        wx.showToast({
          title: "请输入回礼金额",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        that.setData({
          showPopup: true,
          gobackShow: false
        })
      }
    },
    //支付
    addToActivity1(e) {
      var that = this;
      var payWay = e.currentTarget.dataset.id;
      if (payWay == 0) {
        if (that.data.walletBalance < that.data.amountRedEnvelope) {
          wx.showToast({
            title: "钱包余额不足",
            icon: 'none',
            duration: 2000
          })
          return
        } else {
          if (that.data.whetherSetPayPwd) {
            that.setData({
              showPayPwdInput: true,
              payFocus: true
            })
          } else {
            wx.showModal({
              title: '温馨提示',
              content: '为了您的账号安全，请设置支付密码',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  wx.navigateTo({
                    url: '/pages/password/password',
                  })
                }
              }
            })
          }
        }
      }
    },
    addToActivity: function (e) {
      var timestamp = Date.parse(new Date()) / 1000;
      var that = this;
      var payWay = '';
      var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
      var blessings = (that.data.givingAdvice == '' ? '万分感谢，小小心意，请笑纳' : that.data.givingAdvice)
      if (e == 0) {
        payWay = 0
      } else {
        payWay = e.currentTarget.dataset.id;
      }
      if (payWay == 1) {
        var sourceType = 5
      } else {
        var sourceType = ''
      }
      if (that.data.isOver) {
        that.setData({
          isOver: false
        })
        var userId = that.data.userInfo.id
        console.log("支付方式", payWay, app.url)
        var data = {
          birthId: that.data.actid,
          sendId: userId,
          type: 2,
          receiveId: that.data.senderId,
          content: blessings,
          money: that.data.amountRedEnvelope,
          payWay: parseInt(payWay),
          id: that.data.redId,
          sourceType: sourceType,
          prepaymentRecordId: that.data.prepaymentRecordId,
        }
        console.log('传值', data)
        app.req({
          url: 'blessmini/redPacket/returnSalute',
          method: "post",
          showLoad: true,
          data: data,
          success: function (res) {
            console.log("支付", that.data.amountRedEnvelope, res)
            if (res.code == 200 && payWay == 0) {
              that.data.list[that.data.index].isOpen=4
              that.setData({
                showPopup: false,
                isOver: true,
                list:that.data.list
              })
              wx.showToast({
                title: "红包已回赠",
                duration: 2000
              })
              // that.onShow()
              // that.emit()
            } else if (res.code == 200 && payWay == 1) {
              var paydata = res.data;
              console.log("调取", paydata)
              wx.requestPayment({
                timeStamp: paydata.prepayDate.timeStamp,
                nonceStr: paydata.prepayDate.nonceStr,
                package: 'prepay_id=' + paydata.prepayDate.prepay_id,
                signType: 'MD5',
                paySign: paydata.prepayDate.paySign,
                success(res) {
                  that.data.list[that.data.index].isOpen = 4
                  that.setData({
                    outTradeNo: paydata.outTradeNo,
                    showPopup: false,
                    isOver: true,
                    list: that.data.list
                  })
                  wx.showToast({
                    title: "红包已回赠",
                    duration: 2000
                  })
                  // that.onShow()
                },
                fail(res) {
                  that.setData({
                    isOver: true
                  })
                  console.log("支付已取消")
                  console.log(res.data.errMsg)
                }
              })
            } else {
              that.setData({
                isOver: true
              })
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        });
      }
    },
    //预支付
    operationRecord() {
      var timestamp = Date.parse(new Date()) / 1000;
      let that = this
      var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
      var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
      console.log('预支付参数', payPwd, amount)
      app.req({
        url: "blessmini/webPayLog/operationRecord",
        method: "post",
        data: {
          payPwd: payPwd,
          amount: amount
        },
        success: function (res) {
          if (200 == res.code) {
            that.setData({
              prepaymentRecordId: res.msg,
              pwdVal: ''
            });
            console.log('预支付', that.data.prepaymentRecordId)
            that.addToActivity(0)
          } else {
            that.setData({
              pwdVal: ''
            });
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    },
    // 支付密码
    /**
     * 隐藏支付密码输入层
     */
    hidePayLayer: function () {
      this.setData({
        pwdVal: '',
        showPayPwdInput: false,
        payFocus: false
      })
    },
    /**
     * 获取焦点
     */
    getFocus: function () {
      this.setData({ payFocus: true });
    },
    /**
     * 输入密码监听
     */
    inputPwd: function (e) {
      this.setData({ pwdVal: e.detail.value });
      if (this.data.pwdVal.length >= 6) {
        this.setData({
          showPayPwdInput: false,
          payFocus: false
        });
        this.operationRecord()
      }
    },
    // 传递给父组件
    emit: function (e) {
      var that = this;
      this.triggerEvent('myevent') //myevent自定义名称事件，父组件中使用
    },
    login: function (e) {
      var that = this;
      this.triggerEvent('login') //myevent自定义名称事件，父组件中使用
    }

  }
})
